<template>
  <div class="tabs-main">
    <a-row type="flex" style="flex-flow: inherit;">
      <a-col :flex="toggle?'260px':'30px'" style="margin-right: 12px;background-color: #fff;">
        <depart-tree :rootOpened="true" :multi="false" @ok="getTreeData" @toggleBool="toggleBool" />
      </a-col>
      <a-col flex="auto">
        <a-card :bordered="false" style="margin-bottom: 10px">
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper">
            <a-form-model layout="inline" ref="ruleForm" :model="queryParam">
              <z-form-item
                :datas="fieldArr"
                :form="queryParam"
                :gutter="8"
                :submitAction="{show: true, toggle: true, span: 6}"
                @change="getChangeTime"
                @onSubmit="onQuery"
                @onReset="onResetForm"
              />
            </a-form-model>
          </div>
        </a-card>
        <a-card :bordered="false">
          <!-- 操作按钮区域 -->
          <div class="table-operator">
            <div>
              <a-button type="primary" @click="handleRouter('add', 'otherAssistance')">新增</a-button>
              <a-button @click="handleExport">导出</a-button>
            </div>
          </div>
          <!-- 表格展示 -->
          <div class="table-page-content">
            <z-table
              ref="table"
              rowKey="id"
              :showAlert="false"
              :showSelection="true"
              :loading="loading"
              :columns="columns"
              :dataSource="pageData"
              @selectedRow="onSelectedRow"
              @change="onTableChange"
            />
          </div>
          <!--弹窗区域-->
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import * as serviceApi from '@/api/sjsk/clinicmanageService'
import { downLoadFileReader } from '@/utils/export-util/util'
import departTree from '../../modules/departTree';

export default {
  components: { departTree },
  data() {
    return {
      toggle: true,
      loading: false,
      isDisabled: true,
      selectKeys: [],
      queryParam: {},
      fieldArr: [
        { label: '吸毒人员姓名', prop: 'name', tagType: 'input', span: 6 },
        { label: '身份证', prop: 'identityNumber', tagType: 'input', span: 6 },
        { label: '人员类型', prop: 'personType', tagType: 'dict-select', dictCode: 'risk_level_person_type', span: 6},
        { label: '性别', prop: 'sex', tagType: 'dict-select', dictCode: 'sex', span: 6, toggle: false },
        { label: '救助时间', prop: 'time', tagType: 'range-picker', format: 'YYYY-MM-DD', span: 6, toggle: false },
        { label: '救助类型', prop: 'rescueType', tagType: 'dict-select', dictCode: 'rescue_type', span: 6, toggle: false },
      ],
      rescueTypeDictOptions: [
        { text: '失业保险金领取', value: 1, name: 'depositCollection' },
        { text: '灵活就业社保补贴', value: 2, name: 'socialSecuritySubsidy' },
        { text: '脱贫', value: 3, name: 'ridPoor' },
        { text: '低保救助', value: 4, name: 'subsistenceAssistance' },
        { text: '临时救助', value: 5, name: 'temporaryAssistance' },
        { text: '其他救助-慰问走访', value: 6, name: 'otherAssistance' },
        { text: '其他救助-子女教育', value: 7, name: 'otherAssistance' },
        { text: '其他救助-重大疾病帮助', value: 8, name: 'otherAssistance' },
      ],
      columns: [
        {
          title: '姓名',
          dataIndex: 'personName',
          width: 60,
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={text} length={14} />
          },
        },
        {
          title: '性别',
          dataIndex: 'personSex',
          width: 60,
          align: 'center',
          customRender: text => {
            return this.$filterDictTextByCache('sex', text)
          }
        },
        {
          title: '身份证号',
          dataIndex: 'identityNumber',
          width: 80,
          align: 'left',
          customRender: (text) => {
            return <j-ellipsis value={text} length={20} />
          },
        },
        {
          title: '联系电话',
          dataIndex: 'phoneNumber',
          width: 80,
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={text} length={14} />
          },
        },
        {
          title: '人员类型',
          dataIndex: 'personType',
          width: 80,
          align: 'center',
          customRender: text => {
            return this.$filterDictTextByCache('risk_level_person_type', text)
          }
        },
        {
          title: '救助类型',
          dataIndex: 'rescueType',
          width: 80,
          align: 'center',
          customRender: text => {
            return this.$filterDictTextByCache('rescue_type', text)
          }
        },
        {
          title: '救助起止时间',
          dataIndex: 'beginTime',
          width: 120,
          align: 'center',
          customRender: (text, record, index) => {
            return record.beginTime && record.endTime ? record.beginTime +'~'+ record.endTime : '--'
          },
        },
        {
          title: '操作',
          width: 60,
          align: 'center',
          dataIndex: 'action',
          customRender: (text, record, index) => {
            return (
              <a-space size={6}>
                <a-button type="link" style={'padding:0'} onClick={(event) => this.handleRouter('details', record)}> 详情 </a-button>
                {record.rescueType===6 || record.rescueType===7 || record.rescueType===8? <span>
                <a-button type="link" style={'padding:0'} onClick={(event) => this.handleRouter('edit', record)}> 编辑 </a-button>
                <a-button type="link" style={'padding:0px 0px 0px 10px'} onClick={(event) => this.handleOperate(record)}> 删除 </a-button>
                </span>
                  : null
                }
              </a-space>
            )
          },
        },
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData: {}
    }
  },
  created() {},
  async mounted() {
    this.onQuery()
  },
  watch: {
    // 组织机构树-联动筛选人员列表
    'queryParam.departId'(newVal, oldVal){
      this.onQuery()
    }
  },
  methods: {
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.queryParam = {}
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onSelectedRow(keys) {
      this.selectKeys = keys
      this.isDisabled = keys.length > 0 ? false : true
    },
    onTableChange(pagination, pageFilter, sorter) {
      this.pageFilter = Object.assign({}, this.pageFilter, pagination)
      this.refreshTable()
    },
    refreshTable() {
      let {time, ...dataParam} = this.queryParam // 剔除time元素，dataParam最新的对象
      let queryParam = Object.assign({}, dataParam, this.pageFilter)
      this.loading = true
      serviceApi
        .getRescueList(queryParam)
        .then((res) => {
          this.loading = false
          if (res.success) {
            this.pageData = res.result ? res.result : {}
            this.$refs.table.onClearRowKeys()
          } else {
            this.loading = false
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    // 导出
    handleExport(record) {
      let that = this
      let selectList = this.$refs.table.getSelectedRows()
      let idList1 = selectList.map(v => v.id).filter(obj => obj !== null && obj !== undefined && obj !== '')
      let idList2 = record && Object.keys(record).length > 0 && record.id ? [record.id] : []
      let params = Object.assign(
        {},
        {
          idList: selectList.length > 0 ? idList1 : idList2,
          // querySjskPersonVO: this.queryParam
        }
      )
      this.$confirm({
        title: `是否确认导出？`,
        okText: '确定',
        onOk() {
          serviceApi.exportRescue(params).then(async res => {
            const fileName = '帮扶救助记录列表数据.xlsx'
            await downLoadFileReader(res, fileName)
            that.$refs.table.onClearRowKeys()
          })
        }
      })
    },
    // 业务操作-删除
    handleOperate(record) {
      let that = this
      this.$confirm({
        title: `确定删除该条救助数据？`,
        onOk() {
          serviceApi.deleteRescue(record.id).then((res) => {
            if (res.success) {
              that.$message.success(res.message ? res.message : `操作成功！`)
              that.onQuery()
            } else {
              that.$message.warn(res.message ? res.message : `操作失败！`)
            }
          })
            .catch((e) => {
              that.$message.warn('操作失败！')
            })
        }
      })
    },
    handleRouter(type, record) {
      let path = null
      if(record && record instanceof Object) {
        let col = this.rescueTypeDictOptions.find((col, i) => col.value === record.rescueType)
        let name = record instanceof Object?col.name: col
        let id = record instanceof Object?record.id: record
        path = type=='edit'?`/help-rescue/${name}/edit/${id}`:`/help-rescue/${name}/details/${id}`
      } else {
        path = type=='add'?`/help-rescue/${record}/add`:``
      }
      if(!path) return
      this.$router.push({
        path: path,
        query: {}
      })
    },
    // 获取组件的时间， prop为对应的字段，date为选中的时间值
    getChangeTime(prop, date) {
      if(prop === 'time') {
        this.$set( this.queryParam, 'beginTime', date[0] )
        this.$set( this.queryParam, 'endTime', date[1] )
      }
    },
    getTreeData(datas, id) {
      console.log(datas, id)
      console.log(id)
      this.$set( this.queryParam, 'departId', id )
    },
    toggleBool(bool) {
      console.log(bool)
      this.toggle = bool
    },
  }
}
</script>
<style lang="less" scoped>
</style>
